package com.alibaba.dubbo.remoting.msgcodec;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.alibaba.dubbo.remoting.MessageEncode;
import com.alibaba.dubbo.remoting.MessageEncodeRegistry;

public class BridgeEncodeOutputStream extends OutputStream{
	
	private MessageEncode encoder;
	private OutputStream out;
	private ByteArrayOutputStream baos;
	//private MessageEncodeRegistry registry;
	public BridgeEncodeOutputStream(MessageEncode encoder, OutputStream out/*, MessageEncodeRegistry registry*/){
		this.encoder = encoder;
		this.out = out;
		//this.registry = registry;
		if(this.encoder != null){
			this.baos = new ByteArrayOutputStream();
		}
	}
	
	

	@Override
	public void close() throws IOException{
		super.close();
		if(baos != null){
			byte[] data = baos.toByteArray();
			this.encoder.encode(new ByteArrayInputStream(data), out/*, registry*/);
		}
	}
	
	@Override
    public void write(byte[] b, int off, int len) throws IOException {
        if (len == 0) {
            return;
        }
        if(this.encoder != null){
        	baos.write(b, off, len);
        }else{
        	out.write(b, off, len);
        }
    }

    @Override
    public void write(byte[] b) throws IOException {
    	if(this.encoder != null){
        	baos.write(b);
        }else{
        	out.write(b);
        }
    }

    @Override
    public void write(int b) throws IOException {
    	if(this.encoder != null){
        	baos.write(b);
        }else{
        	out.write(b);
        }
    }
}
